import struct
import csv


def parse_binary_data(data):
    # 每两个字节为一个小端数据
    # 8个通道的数据交替排列
    channel_data = [struct.unpack('<h', data[i+j:i+j+2])[0] for i in range(0, len(data), 16) for j in range(0,16,2)]

    # 每通道数据放入一个列表
    channels = [channel_data[i::8] for i in range(8)]

    return channels


def write_to_csv(channels, csv_filename):
    with open(csv_filename, 'a', newline='') as csvfile:
        csv_writer = csv.writer(csvfile)

        # 逐行写入数据
        for row_data in zip(*channels):
            csv_writer.writerow(row_data)


def parse_binary_file_save(file_path,save_path):
    # 创建CSV文件并将CH1.CH2....CH8写入头部
    with open(save_path, 'w', newline='') as csvfile:
        csv_writer = csv.writer(csvfile)
        csv_writer.writerow([f"CH{i}" for i in range(1, 9)])

        # 读取需要解析的二进制文件
    with open(file_path, 'rb') as file:
        while True:
            # 读取前两个字节，检查帧头
            frame_header = file.read(2)
            if not frame_header:
                break  # 文件读取完毕
            if frame_header != b'\xa5\x5a':
                continue  # 不是帧头，继续查找

            # 读取数据缓存长度、数据类型、数据总字节数、通道数
            length, data_type, total_bytes, channel_count = struct.unpack('<IBHH', file.read(9))
            # 读取数据
            data = file.read(total_bytes-2)
            channel_data = parse_binary_data(data)
            # 数据写入CSV文件
            write_to_csv(channel_data, save_path)
            # 检查结尾标识符
            end_marker = file.read(2)
            print(end_marker)
            if end_marker != b'\x00\x16':
                print("Error: Missing end marker")
                break
            # 处理数据，可以根据需要进行相应的操作
            print(f"Frame Data - Length: {length}, Type: {data_type}, Total Bytes: {total_bytes}, Channel Count: {channel_count}, Data: {data}")


if __name__ == "__main__":
    file_path = "data_file.bin"  # 替换为实际的文件路径
    save_path = 'output.csv'
    parse_binary_file_save(file_path,save_path)
